package com.googlesource.gerrit.plugins.examples.servlet;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author zxs
 * @date 2022/5/17
 */
public class PropContainer {
    private static final Logger log = LoggerFactory.getLogger(PropContainer.class);

    private Properties properties;

    private static String charset = "UTF-8";

    private static Map<String, PropContainer> map = new HashMap<String, PropContainer>();

    private PropContainer(String propertiesWay) {
        initConfig(propertiesWay);
    }

    public static PropContainer getInstance(String propertiesWay) {
        if (map.containsKey(propertiesWay)) {
            return map.get(propertiesWay);
        }
        PropContainer p = new PropContainer(propertiesWay);
        map.put(propertiesWay, p);
        return p;
    }

    private void initConfig(String propertiesWay) {
        File file = new File(propertiesWay);
        properties = new Properties();

        if (file.exists()) {
            log.info("配置文件路径---->>{}" + propertiesWay);
            try (InputStreamReader in = new InputStreamReader(new FileInputStream(
                    propertiesWay), charset)) {
                properties.load(in);
            } catch (FileNotFoundException e) {
                System.out.println("配置文件未找到");
            } catch (IOException e) {
                System.out.println("配置文件读取异常");
            } finally {
                System.out.println("加载properties文件内容完成...........");
                System.out.println("properties文件内容：" + properties);
            }
        }

    }

    public String getProperty(String key, String defaultValue) {
        if (properties == null) {
            return defaultValue;
        }
        return properties.getProperty(key, defaultValue);
    }

    public String getProperty(String key) throws RuntimeException {
        String tmp = properties.getProperty(key);
        if (StringUtils.isBlank(tmp)) {
            throw new RuntimeException("属性为空！" + key);
        }
        return tmp;
    }

    public int getInt(String key, int defaultValue) {
        String prop = getProperty(key, "");
        if ("".equals(prop) || !NumberUtils.isDigits(prop)) {
            return defaultValue;
        }
        return Integer.parseInt(prop);
    }

    public boolean containsKey(String key) {
        if (properties != null && properties.containsKey(key)) {
            return true;
        }
        return false;
    }
}